import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_business_1907a/bean/home_banner_bean_result.dart';
import 'package:flutter_business_1907a/bean/home_hot_goods_bean_result.dart';
import 'package:flutter_business_1907a/bean/home_navigator_bean_result.dart';
import 'package:flutter_business_1907a/bean/home_recommond_bean_result.dart';
import 'package:flutter_business_1907a/provider/child_category_provider.dart';
import 'package:flutter_business_1907a/router/application.dart';
import 'package:flutter_business_1907a/service/service_method.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:provider/provider.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    // getHomeNavigator().then(
    //     (value) => print(HomeNavigatorBeanResult.fromJson(value).data.length));
    // getHomeRecommend().then((value) =>
    //     print(HomeRecommondBeanResult.fromJson(value).data.list.length));
    _getHotGoods();
    super.initState();
  }

  //用于更新页面
  int size = 4;
  List<HomeHotGoodsBean> hotGoodsList = [];

  //火爆专区的标题
  Widget hotTitle = Container(
    margin: EdgeInsets.only(top: 1.0),
    padding: EdgeInsets.all(5.0),
    //[5,5,5,5]
    alignment: Alignment.centerLeft,
    decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
    child: Text(
      '火爆专区',
      style: TextStyle(color: Colors.pink),
    ),
  );

  //火爆专区的WarpList
  Widget _hotWrapList() {
    if (hotGoodsList.length != 0) {
      List<Widget> listItemWidget = hotGoodsList.map((e) {
        return InkWell(
          onTap: () {
            Application.router.navigateTo(context,
                '/detail?id=${e.id}');
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: [
                Image.network(
                  e.goodsDefaultIcon,
                  width: ScreenUtil().setWidth(375),
                ),
                Text(
                  e.goodsDesc,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Text('团购价:¥${e.goodsDefaultPrice}元'),
                Text(
                  '原价:¥${e.goodsDefaultPrice + '0'}元',
                  style: TextStyle(
                      color: Colors.black26,
                      decoration: TextDecoration.lineThrough),
                ),
              ],
            ),
          ),
        );
      }).toList();

      return Wrap(
        spacing: 2,
        children: listItemWidget,
      );
    } else {
      return Center(
        child: Text('加载中...'),
      );
    }
  }

  //火爆专区的组合
  Widget _hotGoods() {
    return Container(
      child: Column(
        children: [hotTitle, _hotWrapList()],
      ),
    );
  }

  void _getHotGoods() {
    var formData = '4';
    request('homeHotGoods', formData,false).then((value) {
      List<HomeHotGoodsBean> newList =
          HomeHotGoodsResult.fromJson(value).data.list;
      setState(() {
        hotGoodsList.addAll(newList);
        formData = '8';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334); //IPhone6尺寸基准,设计图尺寸
    return Scaffold(
      appBar: AppBar(title: Text('百姓生活+')),
      body: EasyRefresh(
        onRefresh: () async {},
        onLoad: () async {
          _getHotGoods();
        },
        footer: ClassicalFooter(
            bgColor: Colors.white,
            textColor: Colors.pink,
            infoColor: Colors.pink,
            showInfo: true,
            infoText: '加载中',
            loadReadyText: '加载刷新',
            loadedText: '加载完成',
            loadingText: '正在加载',
            loadText: '下拉加载'
        ),
        header: ClassicalHeader(
            bgColor: Colors.white,
            textColor: Colors.pink,
            infoColor: Colors.pink,
            showInfo: true,
            noMoreText: '',
            infoText: '刷新中',
            refreshReadyText: '下拉刷新',
            refreshedText: '刷新完成',
            refreshingText: '正在刷新',
            refreshText: '下拉刷新'),
        child: ListView(
          children: [
            FutureBuilder(
              future: request('homePageBanner', null,false),
              builder: (context, val) {
                if (val.hasData) {
                  List<Bannerbean> homeBannerList =
                      BannerbeanResult.fromJson(val.data).data;
                  return Column(
                    children: [
                      //放的是具体的轮播图控件
                      SwiperDiy(
                        swiperDataList: homeBannerList,
                      )
                    ],
                  );
                } else {
                  return Center(
                    child: Text('加载中...'),
                  );
                }
              },
            ),
            FutureBuilder(
              future: request('homeNavigator', null,false),
              builder: (context, val) {
                if (val.hasData) {
                  List<HomeNavigatorBean> homeNavigatorList =
                      HomeNavigatorBeanResult.fromJson(val.data).data;
                  return HomeNavigator(
                    navigatorList: homeNavigatorList,
                  );
                } else {
                  return Center(
                    child: Text('加载中'),
                  );
                }
              },
            ),
            FutureBuilder(
                future: request('homeRecommend', null,false),
                builder: (context, val) {
                  if (val.hasData) {
                    List<HomeRecommondBean> recommendList =
                        HomeRecommondBeanResult.fromJson(val.data).data.list;
                    return Recommend(
                      recomendList: recommendList,
                    );
                  } else {
                    return Center(
                      child: Text('加载中...'),
                    );
                  }
                }),
            _hotGoods()
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

//轮播图组件
class SwiperDiy extends StatelessWidget {
  final List<Bannerbean> swiperDataList;

  const SwiperDiy({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(450),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemCount: swiperDataList.length,
        itemBuilder: (context, index) {
          return Image.network(
            '${swiperDataList[index].imagepath}',
            fit: BoxFit.fill, //代表图片全屏拉伸
          );
        },
        pagination: SwiperPagination(), //控制轮播图的小圆点
        autoplay: true, //是否自动轮播
      ),
    );
  }
}

//导航栏
class HomeNavigator extends StatelessWidget {
  final List<HomeNavigatorBean> navigatorList;

  const HomeNavigator({Key key, this.navigatorList}) : super(key: key);

  //girdView的item布局
  Widget _girdViewItemUI(context, HomeNavigatorBean item) {
    return InkWell(
      onTap: () {
        print('点击了导航:${item.id}');
      },
      child: Column(
        children: [
          Image.network(
            '${item.attienImage}',
            width: ScreenUtil().setWidth(95),
          ),
          Text('${item.attenName}')
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(320),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: EdgeInsets.all(4.0),
        children: navigatorList.map((it) {
          return _girdViewItemUI(context, it);
        }).toList(), //拿到数据集合后,将它遍历,把其中每个数值复制给UI的item,再形成一个集合
      ),
    );
  }
}

//商品推荐组件
class Recommend extends StatelessWidget {
  final List<HomeRecommondBean> recomendList;

  const Recommend({Key key, this.recomendList}) : super(key: key);

  //商品推荐的标题
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
      child: Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  //商品推荐单独的item
  Widget _item(HomeRecommondBean item) {
    return InkWell(
      onTap: () {},
      child: Container(
        height: ScreenUtil().setHeight(330),
        width: ScreenUtil().setWidth(250),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(left: BorderSide(width: 1.0, color: Colors.black12))),
        child: Column(
          children: [
            Image.network(item.goodsDefaultIcon),
            Text('¥${item.goodsDefaultPrice}元'),
            Text(
              '¥${item.goodsDefaultPrice}元',
              style: TextStyle(
                  decoration: TextDecoration.lineThrough, color: Colors.grey),
            )
          ],
        ),
      ),
    );
  }

  //商品推荐横向列表组件
  Widget _recommendList() {
    return Container(
      height: ScreenUtil().setHeight(330),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _item(recomendList[index]);
        },
        itemCount: recomendList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(385),
      margin: EdgeInsets.only(top: 10.0),
      child: Column(
        children: [_titleWidget(), _recommendList()],
      ),
    );
  }
}
